function debounceAsync(fn, wait) {
  let timeoutId = null;
  let lastReject = null;

  return function (...args) {
    // 如果存在之前的定时器，清除并拒绝之前的 Promise
    if (timeoutId) {
      clearTimeout(timeoutId);
      lastReject?.(new Error("Debounced function canceled"));
    }

    // 返回新的 Promise
    return new Promise((resolve, reject) => {
      // 保存当前 reject 方法
      lastReject = reject;

      // 设置新的定时器
      timeoutId = setTimeout(async () => {
        try {
          // 执行异步函数并等待结果
          const result = await fn.apply(this, args);
          resolve(result);
        } catch (err) {
          reject(err);
        } finally {
          // 清理状态
          timeoutId = null;
          lastReject = null;
        }
      }, wait);
    });
  };
}
export { debounceAsync };
